<!-- 代码已包含 CSS：使用 TailwindCSS , 安装 TailwindCSS 后方可看到布局样式效果 -->
<template>
  <div class="min-h-screen bg-gray-50">
    <!-- 主体内容 -->
    <div class="max-w-8xl mx-auto px-4 py-8 grid grid-cols-1 lg:grid-cols-3 gap-6">
      <!-- 个人信息卡片 -->
      <div class="bg-white rounded-lg shadow-md p-6 lg:col-span-1">
        <div class="flex flex-col items-center mb-4">
          <div class="relative">
            <img
                :src="`${SERVER_ADDR}/upload/${userInfo.picdir}`"
                class="w-24 h-24 rounded-full object-cover border-4 border-blue-100"
                alt="用户头像"
            >
            <button
                @click="showAvatarModal = true"
                class="absolute bottom-0 right-0 bg-blue-500 text-white rounded-full p-1 hover:bg-blue-600 transition"
            >
              <el-icon><Edit /></el-icon>
            </button>
          </div>
          <h2 class="text-xl font-semibold mt-4 text-gray-800">{{ userInfo.name }}</h2>
        </div>

        <div class="space-y-3">
          <div class="flex justify-between items-center">
            <span class="text-gray-600">出生日期</span>
            <span class="font-medium">{{ userInfo.dateBirth }}</span>
          </div>
          <div class="flex justify-between items-center">
            <span class="text-gray-600">房间号</span>
            <span class="font-medium">{{ userInfo.room.rno }}</span>
          </div>
          <div class="flex justify-between items-center">
            <span class="text-gray-600">联系电话</span>
            <span class="font-medium">{{ userInfo.phone }}</span>
          </div>
          <div class="flex justify-between items-center">
            <span class="text-gray-600">紧急联系人</span>
            <span class="font-medium">{{ userInfo.emergencyContact }}</span>
          </div>
        </div>

        <button
            @click="showEditModal = true"
            class="mt-6 w-full bg-blue-500 hover:bg-blue-600 text-white py-2 px-4 rounded-button whitespace-nowrap transition"
        >
          编辑个人信息
        </button>
      </div>

      <!-- 右侧主要内容 -->
      <div class="lg:col-span-2 space-y-6">
        <!-- 今日餐品订购 -->
        <div class="bg-white rounded-lg shadow-md p-6">
          <div class="flex justify-between items-center mb-4">
            <h2 class="text-xl font-semibold text-gray-800">今日餐品订购</h2>
            <el-button
                type="primary"
                size="small"
                @click="goToMealOrder"
                class="!rounded-button whitespace-nowrap"
            >
              查看全部餐品
            </el-button>
          </div>

          <div v-if="todayOrder.length > 0" class="space-y-4">
            <div
                v-for="order in todayOrder"
                :key="order.id"
                class="flex items-center p-3 border border-gray-100 rounded-lg hover:bg-gray-50 transition"
            >
              <img
                  :src="`${SERVER_ADDR}/upload/${order.orderDetailList[0].goods.pic}`"
                  class="w-16 h-16 rounded-md object-cover"
                  alt="餐品图片"
              >
              <div class="ml-4 flex-1">
                <p class="text-sm text-gray-500">订单号{{ order.id }}</p>
                <p class="text-sm text-gray-500 mt-1">
                  <el-icon class="mr-1"><Clock /></el-icon>
                  {{ order.date }}
                </p>
                <el-tag
                    class="mr-2"
                    type="primary"
                    size="small"
                    v-for="orderDetail in order.orderDetailList">
                  {{orderDetail.goods.name}}
                </el-tag>
              </div>
              <button
                  @click="cancelMealOrder(order.id)"
                  class="text-red-500 hover:text-red-600 transition"
              >
                <el-icon><Close /></el-icon> 取消
              </button>
            </div>
          </div>
          <div v-else class="text-center py-8 text-gray-500">
            <el-icon class="text-4xl"><Document /></el-icon>
            <p class="mt-2">暂无订购餐品</p>
          </div>
        </div>

        <!-- 护理服务预约 -->
        <div class="bg-white rounded-lg shadow-md p-6">
          <div class="flex justify-between items-center mb-4">
            <h2 class="text-xl font-semibold text-gray-800">护理服务预约</h2>
            <el-button
                type="primary"
                size="small"
                @click="goToCareService"
                class="!rounded-button whitespace-nowrap"
            >
              预约新服务
            </el-button>
          </div>

          <div v-if="careServices.length > 0" class="space-y-4">
            <div
                v-for="service in careServices"
                :key="service.id"
                class="p-4 border border-gray-100 rounded-lg hover:bg-gray-50 transition"
            >
              <div class="flex justify-between items-start">
                <div>
                  <h3 class="font-medium text-gray-800">{{ service.service.name }}</h3>
                  <p class="text-sm text-gray-500 mt-1">
                    <el-icon class="mr-1"><User /></el-icon>
                    护理人员: {{ service.medicalStaff.mname }}
                  </p>
                  <p class="text-sm text-gray-500 mt-1">
                    <el-icon class="mr-1"><Clock /></el-icon>
                    预约时间: {{ service.startTime }} - {{ service.endTime }}
                  </p>
                </div>
                <button
                    @click="cancelCareService(service.id)"
                    class="text-red-500 hover:text-red-600 transition"
                >
                  <el-icon><Close /></el-icon> 取消
                </button>
              </div>
            </div>
          </div>
          <div v-else class="text-center py-8 text-gray-500">
            <el-icon class="text-4xl"><Document /></el-icon>
            <p class="mt-2">暂无预约服务</p>
          </div>
        </div>

        <!-- 房间状态 -->
        <div class="bg-white rounded-lg shadow-md p-6">
          <h2 class="text-xl font-semibold text-gray-800 mb-4">房间状态</h2>
          <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
            <div>
              <div class="flex items-center mb-2">
                <el-icon class="text-blue-500 mr-2"><House /></el-icon>
                <span class="text-gray-600">房间号</span>
              </div>
              <p class="text-lg font-medium">{{ roomInfo.rno }}</p>
            </div>
            <div>
              <div class="flex items-center mb-2">
                <el-icon class="text-blue-500 mr-2"><OfficeBuilding /></el-icon>
                <span class="text-gray-600">房型</span>
              </div>
              <p class="text-lg font-medium">{{ roomInfo.type }}</p>
            </div>
            <div>
              <div class="flex items-center mb-2">
                <el-icon class="text-blue-500 mr-2"><Calendar /></el-icon>
                <span class="text-gray-600">居住时长</span>
              </div>
              <p class="text-lg font-medium">{{ roomInfo.duration }}</p>
            </div>
            <div>
              <div class="flex items-center mb-2">
                <el-icon class="text-blue-500 mr-2"><Warning /></el-icon>
                <span class="text-gray-600">房间状态</span>
              </div>
              <p
                  class="text-lg font-medium"
                  :class="{'text-green-500': roomInfo.status === '正常', 'text-yellow-500': roomInfo.status !== '正常'}"
              >
                {{ roomInfo.rstate }}
              </p>
            </div>
          </div>

          <div class="mt-6 grid grid-cols-2 gap-4">
            <button
                @click="requestRoomService('清洁')"
                class="bg-blue-100 hover:bg-blue-200 text-blue-600 py-2 px-4 rounded-button whitespace-nowrap transition"
            >
              <el-icon class="mr-1"><Brush /></el-icon>
              请求清洁
            </button>
            <button
                @click="requestRoomService('维修')"
                class="bg-blue-100 hover:bg-blue-200 text-blue-600 py-2 px-4 rounded-button whitespace-nowrap transition"
            >
              <el-icon class="mr-1"><Tools /></el-icon>
              请求维修
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- 编辑个人信息模态框 -->
    <el-dialog v-model="showEditModal" title="编辑个人信息" width="500px">
      <el-form :model="formInfo" label-width="100px">
        <el-form-item label="姓名">
          <el-input v-model="formInfo.ename" />
        </el-form-item>
        <el-form-item label="出生日期">
          <el-date-picker
              v-model="formInfo.dateBirth"
              type="date"
              placeholder="选择出生日期"
              value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="联系电话">
          <el-input v-model="formInfo.phone" />
        </el-form-item>
        <el-form-item label="紧急联系人">
          <el-input v-model="formInfo.emergencyContact" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showEditModal = false">取消</el-button>
        <el-button type="primary" @click="updateElderlyInfo">保存</el-button>
      </template>
    </el-dialog>

    <!-- 更换头像模态框 -->
    <el-dialog v-model="showAvatarModal" title="更换头像" width="400px">
      <div class="flex justify-center">
        <img
            :src="`${SERVER_ADDR}/upload/${formInfo.picdir}`"
            class="w-32 h-32 rounded-full object-cover border"
            alt="用户头像"
        >
      </div>
      <div class="mt-4">
        <el-upload
            :show-file-list="false"
            :action="SERVER_ADDR + '/user/file/uploadGoods'"
            name="pic"
            :headers="headers"
            :before-upload="beforeAvatarUpload"
            :on-success="handleImageSuccess"
        >
          <el-button type="primary" class="!rounded-button whitespace-nowrap">
            <el-icon class="mr-1"><Upload /></el-icon>
            上传新头像
          </el-button>
        </el-upload>
      </div>
      <template #footer>
        <el-button @click="showAvatarModal = false">取消</el-button>
        <el-button type="primary" @click="saveAvatar">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="js" setup>
import { ref, computed, onMounted } from 'vue';
import {
  Edit, Close, Document, Clock, User, House,
  OfficeBuilding, Calendar, Warning, Brush,
  Tools, Upload
} from '@element-plus/icons-vue';
import {ElMessage, ElMessageBox} from "element-plus";
import elderlyApi from "@/api/user/elderlyApi.js";
import {useTokenStore} from "@/stores/token.js";
import {useUserStore} from "@/stores/user.js";
import router from "@/router/index.js";
import orderApi from "@/api/user/orderApi.js";
import reservationApi from "@/api/user/reservationApi.js";
//服务器路径
const SERVER_ADDR = ref(import.meta.env.VITE_SERVER_ADDR);
const tokenStore = useTokenStore();
const userStore = useUserStore();
//上传图片
const headers = computed(() => {
  let token = tokenStore.tokenStr;
  return {
    token
  }
})
// 用户信息
const userInfo = ref({
  room: {}
});
// 表单信息
const formInfo  = ref({});
// 今日餐品
const todayOrder = ref([]);
// 护理服务
const careServices = ref([]);

// 房间信息
const roomInfo = computed(() => {
  if (!userInfo.value.room) {
    return {};
  }
  userInfo.value.room.type = Number(userInfo.value.room.type) === 1 ? '单人房' : '双人房';
  switch (userInfo.value.room.rstate)
  {
    case 1:
      userInfo.value.room.rstate = '空闲';
      break;
    case 2:
      userInfo.value.room.rstate = '使用中';
      break;
    case 3:
      userInfo.value.room.rstate = '维修中';
      break;
  }
  // 计算入住时间当前时间减去入住时间
  userInfo.value.room.duration = calculateDuration(userInfo.value.checkDate);
  return userInfo.value.room;
})
const calculateDuration = (checkInDate) => {
  const start = new Date(checkInDate);
  const end = new Date();

  let years = end.getFullYear() - start.getFullYear();
  let months = end.getMonth() - start.getMonth();
  let days = end.getDate() - start.getDate();

  if (days < 0) {
    months--;
    const prevMonthLastDay = new Date(end.getFullYear(), end.getMonth(), 0).getDate();
    days += prevMonthLastDay;
  }

  if (months < 0) {
    years--;
    months += 12;
  }

  return `${years}年${months}个月${days}天`;
};
// 模态框状态
const showEditModal = ref(false);
const showAvatarModal = ref(false);



// 取消餐品订单
const cancelMealOrder = (id) => {
  ElMessageBox.confirm('确定要取消该餐品订单吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    let order = {
      id: id,
      status: 5
    }
    orderApi.update(order)
        .then((resp) => {
          if (resp.code === 10000){
            ElMessage.success('已取消餐品订单');
            getTodayOrder()
          }
        })
  })
};

// 取消护理服务
const cancelCareService = (id) => {
  ElMessageBox.confirm('确定要取消该护理服务吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    reservationApi.delete(id)
        .then((resp) => {
          if (resp.code === 10000){
            ElMessage.success('已取消护理服务');
            getAfterService()
          }
        })
  }).catch(() => {});
};

// 上传头像前检查
const beforeAvatarUpload = (file) => {
  const isImage = file.type.startsWith('image/');
  if (!isImage) {
    ElMessage.error('请上传图片文件');
    return false;
  }
  const reader = new FileReader();
  reader.readAsDataURL(file);
  reader.onload = () => {
    userInfo.value.avatar = reader.result;
  };
  return false;
};
// 图片上传处理
const handleImageSuccess = (response, file) => {
  if (response.code === 10000) {
    ElMessage.success('上传成功');
    userInfo.value.picdir = response.data;
  }

};
// 保存头像
const saveAvatar = () => {
  showAvatarModal.value = false;
  ElMessage.success('头像已更新');
};

// 请求房间服务
const requestRoomService = (type) => {
  ElMessage.success(`已提交${type}请求，工作人员将尽快处理`);
};

// 跳转到餐品订购页面
const goToMealOrder = () => {
  ElMessage.success({
    message: "跳转到餐品订购页面",
    duration: 1200,
    onClose: () => {
      router.push('/olddiskes')
    }
  })
};

// 跳转到护理服务页面
const goToCareService = () => {
  ElMessage.success({
    message: "跳转到护理服务页面",
    duration: 1200,
    onClose: () => {
      router.push('/oldserver')
    }
  })
};

// 获取用户个人信息
const getElderlyInfo = () => {
  elderlyApi.eldInfo()
    .then(resp => {
      if (resp.code == 10000){
        userInfo.value = resp.data;
        userStore.updateUser(resp.data);
        formInfo.value = {
          ename: resp.data.ename,
          dateBirth: resp.data.dateBirth,
          phone: resp.data.phone,
          emergencyContact: resp.data.emergencyContact,
          picdir: resp.data.picdir
        };
      }
    })
};
// 修改用户个人信息
const updateElderlyInfo = () => {
  elderlyApi.update(formInfo.value)
    .then(resp => {
      if (resp.code == 10000){
        ElMessage.success('修改成功')
        showEditModal.value = false;
        getElderlyInfo()
      }
    })
}
// 查询当天预约的菜品
const getTodayOrder = () => {
  orderApi.selectByToday()
    .then(resp => {
      if (resp.code == 10000){
        todayOrder.value = resp.data;
      }
    })
};

// 查询未来预定的服务
const getAfterService = () => {
    reservationApi.selectByAfter()
      .then(resp => {
        if (resp.code == 10000){
          careServices.value = resp.data;
        }
      })
}
getAfterService();
getTodayOrder();
getElderlyInfo();
</script>

<style scoped>
/* 自定义滚动条 */
::-webkit-scrollbar {
  width: 6px;
  height: 6px;
}

::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 10px;
}

::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 10px;
}

::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

/* 头像上传按钮样式 */
.el-upload {
  display: block;
  width: 100%;
}
</style>
